<template>
  <s-layout :title="pageTitle" :bgStyle="{ background: '#f8f9fa' }">
    <view class="detail-container">
      <!-- Top Card: Archive Name -->
      <view class="archive-title-card card-shadow" @click="goToUploadPage">
        <fui-icon name="folder" color="#0052d9" size="40"></fui-icon>
        <text class="archive-title-text">{{ archiveName }}</text>
      </view>

      <!-- Loading State -->
      <view v-if="loading" class="status-section loading-state">
        <fui-loading type="col"></fui-loading>
        <text>正在加载文件...</text>
      </view>

      <!-- Empty State -->
      <view
        v-if="!loading && files.length === 0"
        class="status-section empty-state"
      >
        <fui-empty title="暂无文件，快去添加吧~"></fui-empty>
      </view>

      <!-- Waterfall Display Area -->
      <view v-if="!loading && files.length > 0" class="waterfall-container">
        <view
          v-for="(item, index) in files"
          :key="item.id"
          class="waterfall-item card-shadow"
          @longpress="handleLongPress(item, index)"
        >
          <!-- Image Item -->
          <template v-if="item.type === 'image'">
            <view class="image-content" @click="previewImage(index)">
              <image
                class="item-image"
                :src="item.thumbnailUrl || item.url"
                mode="widthFix"
                :lazy-load="true"
              />
            </view>
            <!-- Image Filename Area -->
            <view class="item-filename-area image-filename-area">
              <text class="item-filename">{{
                item.fileName || "图片文件"
              }}</text>
            </view>
            <view class="item-footer image-footer">
              <fui-icon name="clock" color="#888" size="24"></fui-icon>
              <text class="item-time">{{
                formatTimestamp(item.uploadTime)
              }}</text>
            </view>
          </template>

          <!-- Video Item -->
          <template v-else-if="item.type === 'video'">
            <view class="video-content">
              <view class="video-preview">
                <!-- 视频缩略图或默认视频图标 -->

                <fui-upload-video
                  immediate
                  :fileList="item.url?.split(',')"
                  isView
                  background="#ECF5FF"
                  addColor="#d1d1d1"
                  :width="195"
                  :height="195"
                >
                </fui-upload-video>
              </view>
              <view class="item-filename-area video-filename-area">
                <text class="item-filename"
                  >{{ item.fileName || "视频文件" }}
                </text>
              </view>
            </view>
            <view class="item-footer video-footer">
              <fui-icon name="clock" color="#888" size="24"></fui-icon>
              <text class="item-time">{{
                formatTimestamp(item.uploadTime)
              }}</text>
            </view>
          </template>

          <!-- File Item -->
          <template v-else>
            <view class="file-content" @click="downloadFile(item)">
              <view class="file-icon-wrapper">
                <!-- *** MODIFIED: Use image for file icon *** -->
                <image
                  class="file-type-icon"
                  :src="getFileIconImageUrl(item.fileExtension)"
                  mode="aspectFit"
                />
                <!-- *** END MODIFICATION *** -->
              </view>
              <view class="item-filename-area file-filename-area">
                <text class="item-filename">{{
                  item.fileName || "未知文件"
                }}</text>
              </view>
            </view>
            <view class="item-footer file-footer">
              <fui-icon name="clock" color="#888" size="24"></fui-icon>
              <text class="item-time">{{
                formatTimestamp(item.uploadTime)
              }}</text>
              <view class="download-indicator" @click.stop="downloadFile(item)">
                <!-- Use .stop to prevent longpress if clicking download -->
                <fui-icon name="download" color="#0052d9" size="32"></fui-icon>
              </view>
            </view>
          </template>
        </view>
      </view>
    </view>

    <!-- Add Button -->

    <fui-button
      @click="goToUploadPage"
      radius="96rpx"
      btnSize="medium"
      style="
        position: fixed;
        bottom: 50rpx;
        left: 50%;
        transform: translateX(-50%);
        padding: 8px 16px;
        border: none;
        font-size: 30rpx;
      "
      ><text
        class="cicon-add-round-o"
        style="font-size: 40rpx; margin-right: 20rpx"
      ></text>
      <p>添加</p>
    </fui-button>
    <view style="height: 160rpx"></view>
    <!-- Increased padding to avoid overlap with button -->
  </s-layout>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { onLoad, onPullDownRefresh, onUnload } from "@dcloudio/uni-app";
import sheep from "@/sheep"; // Assuming sheep is configured for API calls

// Define the structure for each file item (internal representation)
interface FileItem {
  id: number | string; // Maps to ca_id or item_id in API
  url: string; // Maps to ca_url in API
  thumbnailUrl?: string; // Generated from ca_url for images
  type: "image" | "file" | "video"; // Determined from ca_type in API
  fileName?: string; // Maps to ca_title in API
  fileExtension?: string; // Maps to ca_suffix in API
  uploadTime: number | string | Date; // Maps to createtime in API
}

// --- Page State ---
const companyId = ref<string | null>(null);
const archiveId = ref<number | null>(null);
const archiveName = ref<string>("档案详情");
const allowedUploadTypes = ref<("image" | "file" | "video")[]>([
  "image",
  "file",
  "video",
]);
const loading = ref(true);
const files = ref<FileItem[]>([]); // Holds the fetched and processed files

const pageTitle = computed(() => `${archiveName.value}`);

// --- File Icon Image URLs ---
const pdfIconUrl =
  "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_acrobat.png";
const wordIconUrl =
  "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_word.png";
const genericFileIconUrl =
  "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white.png";
const excelIconUrl =
  "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_excel.png";
const pptIconUrl =
  "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_powerpoint.png";
// 添加视频图标
const videoIconUrl =
  "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/video.png";
const otherFileIconUrl =
  "https://sail-imgs.oss-cn-beijing.aliyuncs.com/fire-uni/file-other%20%281%29.png";

// --- Mock API Functions ---

// Mock Get Details API

// --- Helper Functions ---
const getFileName = (url: string): string => {
  if (!url) return "未知文件";
  try {
    const decodedUrl = decodeURIComponent(url);
    let name = decodedUrl.substring(decodedUrl.lastIndexOf("/") + 1);
    name = name.split("?")[0];
    name = name.split("#")[0];
    return name || "未知文件";
  } catch (e) {
    console.warn("Error decoding or parsing URL:", url, e);
    try {
      let name = url.substring(url.lastIndexOf("/") + 1);
      name = name.split("?")[0];
      name = name.split("#")[0];
      return name || "无法解析的文件名";
    } catch (fallbackError) {
      return "无法解析的文件名";
    }
  }
};

const getFileExtension = (fileName: string): string => {
  if (!fileName) return "";
  const dotIndex = fileName.lastIndexOf(".");
  // Ensure dot is present, not the first character, and not the last character
  if (dotIndex === -1 || dotIndex === 0 || dotIndex === fileName.length - 1) {
    return ""; // Treat as no extension
  }
  return fileName.substring(dotIndex + 1).toLowerCase();
};

const formatTimestamp = (timestamp: number | string | Date): string => {
  let date: Date;

  if (timestamp instanceof Date) {
    date = timestamp;
  } else if (typeof timestamp === "number") {
    // Assume seconds if < 11 digits, otherwise milliseconds
    const ts = timestamp.toString().length < 11 ? timestamp * 1000 : timestamp;
    date = new Date(ts);
  } else if (typeof timestamp === "string") {
    // Try parsing common date/datetime string formats
    // Replace hyphens with slashes for better compatibility with `new Date()`
    const dateString = timestamp.replace(/-/g, "/");
    date = new Date(dateString);
  } else {
    return "未知时间";
  }

  if (isNaN(date.getTime())) {
    console.warn("Invalid date value received:", timestamp);
    return "未知时间"; // Invalid date
  }

  // Simple YYYY-MM-DD HH:mm format
  const Y = date.getFullYear();
  const M = (date.getMonth() + 1).toString().padStart(2, "0");
  const D = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  return `${Y}-${M}-${D} ${h}:${m}`;
};

// *** NEW Function: Get Image URL for File Icon ***
const getFileIconImageUrl = (extension: string | undefined): string => {
  if (!extension) {
    return otherFileIconUrl; // No extension or unknown
  }
  switch (extension.toLowerCase()) {
    case "pdf":
      return pdfIconUrl;
    case "doc":
    case "docx":
      return wordIconUrl;
    case "xls":
    case "xlsx":
      return excelIconUrl;
    case "ppt":
    case "pptx":
      return pptIconUrl;
    case "mp4":
    case "avi":
    case "mov":
    case "wmv":
    case "flv":
    case "mkv":
      return videoIconUrl;
    default:
      return otherFileIconUrl; // Fallback for all other types
  }
};

// --- API Call Logic ---
const fetchArchiveDetails = async () => {
  if (!archiveId.value || !companyId.value) {
    console.error("Missing archiveId or companyId");
    uni.showToast({ title: "无法加载详情: 参数错误", icon: "none" });
    loading.value = false;
    return;
  }

  loading.value = true;
  files.value = []; // Clear previous files

  try {
    const response = await sheep.$api.qy_index.archivalDetail({
      company_id: companyId.value,
      item_id: archiveId.value,
    });

    console.log("response", response.archivalList);
    // Check if response contains data (assuming array response)
    if ((response.code = 200)) {
      const fetchedFiles: FileItem[] = [];

      response.archivalList.forEach((item: any) => {
        // Map the new API response format to our FileItem structure
        if (!item.ca_url) {
          console.warn("Skipping item due to missing url:", item);
          return;
        }

        const fileName = item.ca_title || getFileName(item.ca_url);
        // 判断是否为视频类型
        let itemType: "image" | "file" | "video" = "file";
        if (item.ca_type === "image") {
          itemType = "image";
        } else if (
          item.ca_type === "video" ||
          isVideoFile(item.ca_url || fileName)
        ) {
          itemType = "video";
        }

        const fileExtension = item.ca_suffix || getFileExtension(fileName);
        const uploadTime = item.createtime || Date.now();

        const fileItem: FileItem = {
          id: item.ca_id || item.item_id, // Use either ca_id or item_id as fallback
          url: item.ca_url,
          thumbnailUrl: itemType === "image" ? item.ca_url : undefined,
          type: itemType,
          fileName: fileName,
          fileExtension: fileExtension,
          uploadTime: uploadTime,
        };
        fetchedFiles.push(fileItem);
      });

      fetchedFiles.sort((a, b) => {
        const dateA = new Date(
          formatTimestamp(a.uploadTime).replace(/-/g, "/")
        ).getTime();
        const dateB = new Date(
          formatTimestamp(b.uploadTime).replace(/-/g, "/")
        ).getTime();
        if (isNaN(dateA) || isNaN(dateB)) return 0;
        return dateB - dateA;
      });

      files.value = fetchedFiles;
      console.log("Processed files:", files.value);
    } else {
      console.error(
        "Failed to fetch archive details or invalid data format:",
        response
      );
      uni.showToast({ title: "加载文件列表失败", icon: "none" });
    }
  } catch (error) {
    console.error("Error fetching archive details:", error);
    uni.showToast({ title: "网络错误，请稍后重试", icon: "none" });
  } finally {
    loading.value = false;
    uni.stopPullDownRefresh();
  }
};

// 判断文件是否为视频
const isVideoFile = (filename: string): boolean => {
  if (!filename) return false;
  const videoExtensions = [
    ".mp4",
    ".avi",
    ".mov",
    ".wmv",
    ".flv",
    ".mkv",
    ".webm",
    ".m4v",
    ".3gp",
  ];
  const lowerFilename = filename.toLowerCase();
  return videoExtensions.some((ext) => lowerFilename.endsWith(ext));
};

// --- User Actions ---
const previewImage = (index: number) => {
  const clickedItem = files.value[index];
  if (clickedItem?.type !== "image") return;

  const allImageUrls = files.value
    .filter((item) => item.type === "image")
    .map((item) => item.url);

  const currentImageIndex = allImageUrls.findIndex(
    (url) => url === clickedItem.url
  );

  if (allImageUrls.length > 0) {
    uni.previewImage({
      urls: allImageUrls,
      current: currentImageIndex >= 0 ? currentImageIndex : 0,
      indicator: "number",
      loop: true,
    });
  }
};

const downloadFile = (fileItem: FileItem) => {
  if (!fileItem.url) return;

  uni.showLoading({ title: "正在准备下载...", mask: true });

  uni.downloadFile({
    url: fileItem.url,
    success: (res) => {
      if (res.statusCode === 200) {
        const tempFilePath = res.tempFilePath;
        console.log("文件下载成功:", tempFilePath);
        uni.hideLoading(); // Hide loading *before* trying to open/save

        uni.openDocument({
          filePath: tempFilePath,
          success: () => {
            console.log("文件打开成功");
          },
          fail: (openErr) => {
            console.error("直接打开文件失败:", openErr);
            // Fallback: Prompt user that download is complete, they can find it manually or try saving
            uni.showModal({
              title: "下载完成",
              content: `文件 '${
                fileItem.fileName || "未知文件"
              }' 已下载。您可以在系统的下载目录或通过分享菜单找到它。`,
              showCancel: false,
              confirmText: "知道了",
            });
          },
        });
      } else {
        uni.hideLoading();
        console.error("下载失败, 服务器状态码:", res.statusCode);
        uni.showToast({ title: `下载失败 (${res.statusCode})`, icon: "none" });
      }
    },
    fail: (err) => {
      uni.hideLoading();
      console.error("下载请求失败:", err);
      uni.showToast({ title: "下载失败, 请检查网络", icon: "none" });
    },
  });
};

const goToUploadPage = () => {
  if (!companyId.value || !archiveId.value) {
    uni.showToast({ title: "参数丢失，无法跳转", icon: "none" });
    return;
  }
  const typesParam = allowedUploadTypes.value.join(",");
  uni.navigateTo({
    url: `/pages/qy/archives/upload?company_id=${companyId.value}&item_id=${
      archiveId.value
    }&archiveName=${encodeURIComponent(
      archiveName.value
    )}&allowedTypes=${typesParam}`,
  });
};

// Long Press Handler for Deletion
const handleLongPress = (item: FileItem, index: number) => {
  console.log("Long pressed item:", item.id, item.fileName);
  uni.showModal({
    title: "确认删除",
    content: `确定要删除文件 "${
      item.fileName || (item.type === "image" ? "图片" : "文件")
    }" 吗？此操作不可恢复。`,
    confirmColor: "#fa3534", // Red color for delete confirmation
    success: async (res) => {
      if (res.confirm) {
        console.log("用户点击确定删除");
        await deleteItem(item, index);
      } else if (res.cancel) {
        console.log("用户点击取消");
      }
    },
  });
};

// Actual Deletion Logic
const deleteItem = async (item: FileItem, index: number) => {
  if (!archiveId.value || !companyId.value) {
    uni.showToast({ title: "参数错误，无法删除", icon: "none" });
    return;
  }

  uni.showLoading({ title: "正在删除...", mask: true });

  try {
    // *** Updated to match new API structure ***
    const response = await sheep.$api.qy_index.delArchival({
      archive_id: archiveId.value,
      company_id: companyId.value,
      ca_id: item.id, // Use the id from our FileItem (which comes from ca_id in API)
    });
    console.log("API Response:", response);
    // Assuming success response has either error:0 or code:200
    if (response.error == 0 || response.code == 200) {
      // Remove item from the local list *after* successful API call
      files.value.splice(index, 1);
      uni.hideLoading();
      uni.showToast({ title: response.msg || "删除成功", icon: "success" });
      console.log(`Item ${item.id} deleted successfully.`);
    } else {
      uni.hideLoading();
      console.error("Failed to delete item:", response.msg);
      uni.showToast({ title: response.msg || "删除失败", icon: "none" });
    }
  } catch (error) {
    uni.hideLoading();
    console.error("Error deleting item:", error);
    uni.showToast({ title: "删除操作失败，请检查网络", icon: "none" });
  }
};

// --- Lifecycle ---
// 创建事件监听函数
const handleDataUpdate = () => {
  console.log('收到数据更新事件，准备刷新数据');
  // 使用延迟确保DOM已完全渲染
  setTimeout(() => {
    if (companyId.value && archiveId.value) {
      console.log('开始刷新档案详情数据');
      loading.value = true; // 显示加载状态
      fetchArchiveDetails();
    }
  }, 100); // 短暂延迟确保DOM已渲染
};

// 在页面卸载时移除事件监听
onUnload(() => {
  console.log('页面卸载，移除事件监听');
  uni.$off('archiveDataUpdated', handleDataUpdate);
});

// 在页面加载时设置事件监听
onLoad((options: any) => {
  // 注册事件监听
  uni.$on('archiveDataUpdated', handleDataUpdate);
  
  // Get parameters from navigation
  companyId.value = options.company_id || options.companyId || null;
  archiveId.value =
    options.item_id ||
    (options.archiveId ? parseInt(options.archiveId, 10) : null);
  archiveName.value =
    options.ca_title ||
    (options.archiveName
      ? decodeURIComponent(options.archiveName)
      : "档案详情");

  // 解析原始数据 - Try to use direct data if provided or parsed from options
  if (options.rawData) {
    try {
      const rawData = JSON.parse(decodeURIComponent(options.rawData));
      console.log("Parsed raw data:", rawData);

      // Directly use the parsed data if it's in the expected format
      if (rawData && Array.isArray(rawData) && rawData.length > 0) {
        const sampleItem = rawData[0];
        if (sampleItem.ca_id && sampleItem.ca_url) {
          // If we have the right data format, set files directly
          files.value = rawData.map((item: any) => {
            const fileName = item.ca_title || getFileName(item.ca_url);
            const itemType: "image" | "file" | "video" =
              item.ca_type === "image"
                ? "image"
                : item.ca_type === "video" ||
                  isVideoFile(item.ca_url || fileName)
                ? "video"
                : "file";
            const fileExtension = item.ca_suffix || getFileExtension(fileName);
            const uploadTime = item.createtime || Date.now();

            return {
              id: item.ca_id || item.item_id,
              url: item.ca_url,
              thumbnailUrl: itemType === "image" ? item.ca_url : undefined,
              type: itemType,
              fileName: fileName,
              fileExtension: fileExtension,
              uploadTime: uploadTime,
            };
          });

          // Sort the files by upload time
          files.value.sort((a, b) => {
            const dateA = new Date(
              formatTimestamp(a.uploadTime).replace(/-/g, "/")
            ).getTime();
            const dateB = new Date(
              formatTimestamp(b.uploadTime).replace(/-/g, "/")
            ).getTime();
            if (isNaN(dateA) || isNaN(dateB)) return 0;
            return dateB - dateA;
          });

          loading.value = false;
          return; // Skip fetchArchiveDetails if we already have the data
        }
      }
    } catch (e) {
      console.error("Error parsing raw data:", e);
    }
  }

  const typesString = options.allowedTypes || "";
  if (typesString) {
    allowedUploadTypes.value = typesString
      .split(",")
      .filter(
        (t: string) => t === "image" || t === "file" || t === "video"
      ) as ("image" | "file" | "video")[];
  }
  if (allowedUploadTypes.value.length === 0) {
    allowedUploadTypes.value = ["image", "file", "video"];
  }
  console.log("Parsed allowedUploadTypes:", allowedUploadTypes.value);

  if (companyId.value && archiveId.value) {
    fetchArchiveDetails();
  } else {
    console.error(
      "Missing required parameters in onLoad: companyId=",
      companyId.value,
      "archiveId=",
      archiveId.value
    );
    uni.showToast({
      title: "无法加载页面: 参数缺失",
      icon: "error",
      duration: 3000,
    });
    loading.value = false;
  }
});

// --- Pull Down Refresh ---
onPullDownRefresh(() => {
  console.log("Pull down refresh triggered");
  fetchArchiveDetails(); // Re-fetch data
});
</script>

<style lang="scss" scoped>
.detail-container {
  padding: 20rpx 30rpx;
  padding-bottom: 180rpx;
  /* Add padding to prevent overlap with fixed button */
}

.card-shadow {
  box-shadow: 0 6rpx 18rpx rgba(0, 45, 115, 0.08);
  transition: box-shadow 0.3s ease-in-out, transform 0.2s ease-out;
  /* Add transform transition */
}

.archive-title-card {
  display: flex;
  align-items: center;
  gap: 15rpx;
  background-color: #ffffff;
  padding: 25rpx 30rpx;
  border-radius: 16rpx;
  margin-bottom: 35rpx;
  border-left: 8rpx solid #0052d9;
  cursor: pointer;

  .archive-title-text {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    flex-grow: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  &:active {
    transform: scale(0.99); // Subtle press effect
    box-shadow: 0 4rpx 12rpx rgba(0, 45, 115, 0.1);
  }
}

.status-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 100rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;

  &.loading-state text {
    margin-top: 16rpx;
  }

  // Customize empty state if needed
  &.empty-state {
    :deep(.fui-empty__title) {
      color: #888;
    }
  }
}

.waterfall-container {
  column-count: 2;
  column-gap: 20rpx;
}

.waterfall-item {
  background-color: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
  margin-bottom: 20rpx;
  break-inside: avoid;
  display: flex;
  flex-direction: column;
  cursor: pointer; // Indicate interactivity

  // Active state for touch/click
  &:active {
    transform: scale(0.98); // Press effect
  }

  .image-content,
  .video-content,
  .file-content {
    position: relative;
    width: 100%;
    min-height: 100rpx;
  }

  .image-content {
    background-color: #f0f0f0;

    .item-image {
      display: block;
      width: 100%;
      height: auto;
    }
  }

  .video-content {
    background-color: #000;
  }

  .file-content {
    padding: 25rpx 20rpx 0rpx 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 15rpx;
    min-height: 150rpx;
    justify-content: center;
    background-color: #f9f9f9;

    .file-icon-wrapper {
      margin-bottom: 10rpx;
      line-height: 0; // Prevents extra space below image sometimes
    }

    .file-type-icon {
      width: 100rpx; // Adjust size as desired
      height: 100rpx; // Adjust size as desired
      display: block; // Good practice for images
    }
  }

  .item-filename-area {
    padding: 10rpx 20rpx;
    background-color: #ffffff;

    .item-filename {
      font-size: 26rpx;
      color: #333;
      font-weight: 500;
      line-height: 1.4;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: break-all;
      text-align: left;
      min-height: 1.4em * 1; // Ensure minimum height for 1 line
    }
  }

  // Add border top only if filename area exists before footer
  .item-filename-area + .item-footer {
    border-top: 1rpx solid #eee;
  }

  .image-filename-area {
    padding-bottom: 10rpx;
  }

  .file-filename-area {
    padding-top: 0;
    padding-bottom: 15rpx;
    width: 100%;
  }

  .item-footer {
    padding: 12rpx 20rpx;
    background-color: #f9f9f9;
    display: flex;
    align-items: center;
    gap: 8rpx;
    border-radius: 0 0 16rpx 16rpx; // Round bottom corners if footer is last

    .item-time {
      font-size: 22rpx;
      color: #888;
      flex-grow: 1;
    }

    &.file-footer .download-indicator {
      cursor: pointer;
      margin-left: auto;
      padding: 5rpx; // Increase clickable area slightly
      display: flex; // Helps center icon if padding is added
      align-items: center;
      justify-content: center;

      &:active {
        // Add visual feedback for download icon press
        opacity: 0.7;
      }
    }
  }

  // Ensure footer has rounded corners if filename area is NOT present
  .image-content + .item-footer {
    border-radius: 0 0 16rpx 16rpx;
    border-top: 1rpx solid #eee; // Add top border if no filename area
  }

  // Ensure image content has rounded top corners if filename area IS present
  .image-content + .item-filename-area .item-image {
    border-radius: 0; // Remove image rounding if filename area follows
  }

  // Ensure image and video content has rounded top corners if no filename area follows
  .image-content + .item-footer .item-image,
  .video-content + .item-footer .video-thumbnail {
    border-radius: 16rpx 16rpx 0 0;
  }
}

// Floating Action Button Style
.add-button {
  position: fixed !important;
  /* Use important if necessary to override framework styles */
  bottom: 50rpx;
  right: 30rpx;
  /* Position to the right */
  width: auto !important;
  /* Allow button to size based on content */
  min-width: 110rpx;
  /* Ensure minimum size */
  height: 110rpx;
  /* Make it circular */
  border-radius: 50% !important;
  /* Circular shape */
  padding: 0 !important;
  /* Remove default padding */
  display: flex !important;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 20rpx rgba(0, 82, 217, 0.3);
  z-index: 99;
  /* Ensure it's above other content */
  // background-color: $fui-color-primary; // Use theme primary color
  color: #fff;

  .add-button-icon {
    font-size: 50rpx !important; // Larger icon
    margin-right: 0 !important; // Remove margin if only icon
  }

  // Hide text if you only want the icon
  p {
    display: none;
  }

  &:active {
    //  background-color: darken($fui-color-primary, 10%); // Darken on press
  }
}

// Style for the add icon itself (if using cicon-)
.cicon-add-round-o {
  font-size: 40rpx;
}

.video-content {
  position: relative;
  width: 100%;
  background-color: #000;
  padding: 0;
  overflow: hidden;
}

.video-preview {
  position: relative;
  width: 100%;
  aspect-ratio: 16/9;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #171717;
}

.video-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2;
}

.video-filename-area {
  padding: 15rpx 20rpx;
  background-color: #ffffff;
}

.video-footer {
  background-color: #f5f5f5;
}

.play-indicator {
  cursor: pointer;
  margin-left: auto;
  padding: 5rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  &:active {
    opacity: 0.7;
  }
}
</style>
